// API 基础配置
export const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";

// API 端点
export const API_ENDPOINTS = {
  // 文章相关
  POSTS: `${API_BASE_URL}/api/posts`,
  POST_BY_SLUG: (slug: string) => `${API_BASE_URL}/api/posts/${slug}`,

  // 认证相关
  LOGIN: `${API_BASE_URL}/api/auth/login`,
  REGISTER: `${API_BASE_URL}/api/auth/register`,
} as const;

// 通用请求函数
export async function apiRequest<T>(
  url: string,
  options: RequestInit = {}
): Promise<T> {
  const response = await fetch(url, {
    headers: {
      "Content-Type": "application/json",
      ...options.headers,
    },
    ...options,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: "请求失败" }));
    throw new Error(error.message || "网络请求失败");
  }

  return response.json();
}

// 带认证的请求函数
export async function authenticatedRequest<T>(
  url: string,
  options: RequestInit = {}
): Promise<T> {
  const { getAuthHeaders } = await import("./auth");
  const authHeaders = getAuthHeaders();

  return apiRequest<T>(url, {
    ...options,
    headers: {
      ...authHeaders,
      "Content-Type": "application/json",
      ...options.headers,
    },
  });
}
